package com.bytech.admin.biz.controller.article;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytech.admin.biz.exception.BlogAdminRuntimeException;
import com.bytech.common.config.UploadConfig;
import com.bytech.common.annotation.UserAgent;
import com.bytech.common.biz.controller.base.BasicController;
import com.bytech.common.biz.entity.article.Article;
import com.bytech.common.biz.entity.article.ArticleDto;
import com.bytech.common.biz.entity.article.ArticleQuery;
import com.bytech.common.biz.entity.articleTag.ArticleTag;
import com.bytech.common.biz.entity.base.BaseResult;
import com.bytech.common.biz.entity.base.BlogResultStatus;
import com.bytech.common.biz.entity.blogUser.BlogUserAgent;
import com.bytech.common.biz.enums.UploadResourceTypeEnum;
import com.bytech.common.biz.enums.article.ArticleStatusEnum;
import com.bytech.common.biz.service.remote.article.RemoteArticleService;
import com.bytech.common.biz.thirdparty.gallery.service.GalleryApiClient;
import com.bytech.common.utils.StringUtils;

import com.google.common.collect.Lists;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author Zhao
 * @Create 2021/8/10 17:40
 */
@Controller
@RequestMapping("/article")
public class ArticleController extends BasicController {

    @Resource
    private RemoteArticleService remoteArticleService;
    @Resource
    private UploadConfig uploadConfig;
    @Resource
    private GalleryApiClient galleryApiClient;

    @GetMapping("/list")
    public String toArticleList(Model model) {
        model.addAttribute("articleStatus", ArticleStatusEnum.validValues());
        return "/article/articles";
    }

    @GetMapping("/pageByQuery")
    @ResponseBody
    public BaseResult<Page<ArticleDto>> pageArticleByQuery(ArticleQuery<Article> articleQuery) {
        return remoteArticleService.pageArticleByQuery(articleQuery);
    }

    @GetMapping({ "/save/{id}", "/save/" })
    public String toSaveArticle(@PathVariable(name = "id", required = false) String id, Model model) {
        ArticleDto articleDto = new ArticleDto();
        if (StringUtils.isBlank(id)) {
            articleDto.setId(StringUtils.getUUID32()); // ID 为空视为新建文章，分配一个新的 UUID 以供上传图片使用
        }
        articleDto.setIsOriginal(true); // 默认原创
        if (!StringUtils.isBlank(id)) {
            BaseResult<ArticleDto> queryResult = remoteArticleService.getArticleById(id);
            if (queryResult.isFailure()) {
                throw new BlogAdminRuntimeException(BlogResultStatus.ofCode(queryResult.getCode()));
            }
            articleDto = queryResult.getData();
        }
        List<ArticleTag> articleTagList = remoteArticleService.getAllUsableTag();
        model.addAttribute("tagList", articleTagList);
        model.addAttribute("article", articleDto);
        model.addAttribute("articleStatus", ArticleStatusEnum.validValues());
        return "/article/save";
    }

    @PostMapping("/save/")
    @ResponseBody
    public BaseResult<Article> doSaveArticle(ArticleDto article, @UserAgent BlogUserAgent userAgent) {
        if (!StringUtils.isBlank(article.getSummary())) {
            String summary = article.getSummary();
            article.setSummary(summary.replaceAll("\n", " ").replaceAll(" ", "")); // 处理所有的回车
        }
        article.setCreator(userAgent.getId());
        return remoteArticleService.saveArticle(article);
    }

    @PostMapping("/delete")
    @ResponseBody
    public BaseResult<String> doDeleteArticle(String id) {
        return remoteArticleService.deleteArticleById(id);
    }

    /**
     * 物理删除
     */
    @PostMapping("/physicalDelete")
    @ResponseBody
    public BaseResult<String> physicalDeleteArticleById(String id) {
        return remoteArticleService.physicalDeleteArticleById(id);
    }

    @PostMapping("/uploadImage")
    @ResponseBody
    public BaseResult<?> doUploadArticleImage(MultipartFile file) {
        if (file == null) {
            return BaseResult.error("文件不能为空").build();
        }
        List<MultipartFile> files = Lists.newArrayList();
        files.add(file);
        return galleryApiClient.doUploadImages(files, UploadResourceTypeEnum.ARTICLE, fileUrlList -> {
            String fullUrl = null;
            if (!CollectionUtils.isEmpty(fileUrlList)) {
                fullUrl = fileUrlList.get(0);
            }
            return BaseResult.success("上传成功！").data(fullUrl).build();
        });
    }
}
